package com.kehutong.wxapi.util;

import com.kehutong.common.urlconfig.UrlConfig;
import org.coraframework.http.HttpClient;
import org.coraframework.inject.Singleton;
import org.coraframework.json.JSON;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.util.CallBack;

/**
 * 客户企业微信客户端请求对象
 */
@Singleton
public class KhtClient extends UrlConfig {
    static final Logger logger = LoggerFactory.getLogger(KhtClient.class);
    protected KhtClient() {
        super("tencent", "work_url");
    }
    @Override
    public JSONObject get(String page, CallBack<HttpClient> callBack) throws Exception {
        long beginTime=System.currentTimeMillis();
        String url=getUrl() + page;
        if(logger.isInfoEnabled()){
            logger.info("-------------开始请求腾讯接口: url:{}",url);
        }
        final HttpClient httpClient = HttpClient.create(url);
        callBack.call(httpClient);
        String text = httpClient.get();

        if (httpClient.getResponseCode() != 200) {
            return httpError(httpClient.getResponseCode(), "http状态错误");
        }
        if(logger.isInfoEnabled()){
            logger.info("-------------结束请求腾讯接口: url:{},用时{}毫秒",url,System.currentTimeMillis()-beginTime);
        }
        return JSON.parseObject(text);
    }

    @Override
    public JSONObject post(String page, CallBack<HttpClient> client) throws Exception {
        final HttpClient httpClient = HttpClient.create(getUrl() + page);
        client.call(httpClient);


        String text = httpClient.get();
        if (httpClient.getResponseCode() != 200) {
            return httpError(httpClient.getResponseCode(), "http状态错误");
        }
        return JSON.parseObject(text);
    }

    public JSONObject httpError(int code, String message) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", code);
        jsonObject.put("message", message);

        return jsonObject;
    }
}
